#include<iostream>
#include<unistd.h>
#include<thread>
#include<pthread.h>
using namespace std;

int tickets=1000;
pthread_mutex_t mx;

void* threadrout(void* arg)
{
    char* tname=(char*)arg;
    while(1)
    {
        pthread_mutex_lock(&mx);
        //while中包裹的都是临界区
        if(tickets>0)
        {
            usleep(1000);
            cout<<tname<<" : 抢到一张，还剩 : "<<--tickets<<endl;
            pthread_mutex_unlock(&mx);
        }
        else
        {
            pthread_mutex_unlock(&mx);
            break;

        }
        usleep(1000);//增加一个休息轮转的时间
    }
}

int main()
{
    pthread_mutex_init(&mx,NULL);
    pthread_t t1,t2,t3,t4;
    pthread_create(&t1,NULL,threadrout,(void*)"t1");
    pthread_create(&t2,NULL,threadrout,(void*)"t2");
    pthread_create(&t3,NULL,threadrout,(void*)"t3");
    pthread_create(&t4,NULL,threadrout,(void*)"t4");

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    pthread_join(t4,NULL);

    pthread_mutex_destroy(&mx);

    return 0;
}
